package com.uyayo.oms.shiro;

import com.github.pagehelper.util.StringUtil;
import com.uyayo.system.authority.entity.SysResource;
import com.uyayo.system.authority.pojo.SysRolePO;
import com.uyayo.system.authority.entity.SysUser;
import com.uyayo.system.authority.pojo.SysUserPO;
import com.uyayo.system.authority.service.SysUserService;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import java.util.HashSet;
import java.util.Set;

/**
 * Created by hfj
 * on 2017/4/21.
 */
public class MyShiroRealm extends AuthorizingRealm {
    private static final Logger logger = Logger.getLogger(MyShiroRealm.class);

    @Autowired
    @Qualifier(value="sysUserService")
    private SysUserService sysUserService;//身份资格

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        logger.info("授权认证：" + principals.getRealmNames());
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Object obj = principals.getPrimaryPrincipal();
        if(obj instanceof SysUser) {
            SysUser user = (SysUser) obj;
            SysUserPO userToRole = this.sysUserService.getUserToRole(user.getId());
            Set<String> set = new HashSet<>();
            for (SysRolePO role : userToRole.getRoles()) {
                //基于用户名的角色信息
                info.addRole(role.getName());
                //基于角色的权限信息
                for (SysResource resource : role.getResources()) {
                    if (StringUtil.isNotEmpty(resource.getPermission())) {
                        set.add(resource.getPermission());
                    }
                }
            }
            info.setStringPermissions(set);
        }
        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        ManagerUsernamePasswordToken managerUsernamePasswordToken = (ManagerUsernamePasswordToken) token;

        //获取用户的输入的账号.
        String username = (String)token.getPrincipal();
        SysUser user = sysUserService.getUserByLoginname(username);
        if(user==null) {
            throw new UnknownAccountException();
        }
        if (0==user.getStatus() || 1==user.getStatus()) {
            throw new LockedAccountException(); // 帐号锁定
        }
        if (!user.getPassword().equals(new String(managerUsernamePasswordToken.getPassword()))) {
            throw new AuthenticationException();
        }
        logger.info("authc username:" + user.getLoginname() + " pwd:" + user.getPassword() + " getName:" + getName());

        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                user, //用户
                user.getPassword(), //密码
                new MySimpleByteSource(username.getBytes()),
                getName()  //realm name
        );
        // 当验证都通过后，把用户信息放在session里
        Session session = SecurityUtils.getSubject().getSession();
        session.setAttribute("userSession", user);
        session.setAttribute("userSessionId", user.getId());
        return authenticationInfo;
    }

    /**
     * 指定principalCollection 清除
     */
  /*  public void clearCachedAuthorizationInfo(PrincipalCollection principalCollection) {

        SimplePrincipalCollection principals = new SimplePrincipalCollection(
                principalCollection, getName());
        super.clearCachedAuthorizationInfo(principals);
    }
*/
}
